home *** CD-ROM | disk | FTP | other *** search
- Path: mail2news.demon.co.uk!wbriscoe.demon.co.uk
- From: walter briscoe <walter@wbriscoe.demon.co.uk>
- Newsgroups: comp.std.c
- Subject: Re: Restrictions on qsort compare function?
- Date: Fri, 22 Mar 96 08:00:00 GMT
- Distribution: world
- Message-ID: <827481600snz@wbriscoe.demon.co.uk>
- References: <4iokop$h4p@lyra.csx.cam.ac.uk>
- Reply-To: walter@wbriscoe.demon.co.uk
- X-NNTP-Posting-Host: wbriscoe.demon.co.uk
- X-Newsreader: Demon Internet Simple News v1.30
- X-Mail2News-Path: wbriscoe.demon.co.uk
-
- In article <4iokop$h4p@lyra.csx.cam.ac.uk>
- jkb@mrc-lmb.cam.ac.uk "James Bonfield" writes:
-
- > Are there any limitations on what the sort function passed over to qsort can
- > do or return? I know it's meant to return < 0, 0 or > 0 for the various
- > compare operations, but which you return is purely up to your own comparison
- > system.
- >
-
- [snip]
-
- > static int sort_func(const void *pa, const void *pb)
- > {
- > const int *a = (int *)pa;
- > const int *b = (int *)pb;
- >
- > return *a > *b;
- >
- > }
-
- You need a function which returns "an integer less than, equal to, or
- greater than zero if the first argument is considered to be respectively
- less than, equal to, or greater than the second" [ ANSI/ISO 9899-1990
- 7.10.5.2].
-
- sort_funct returns 0, 0, and 1, respectively for the 3 cases enumerated.
-
- Brevity is satisfied by:
- return *a < *b ? -1 : *a > *b;
-
- You may find that conformity to the interface is better shown by:
- return (*a < *b) ? -1 : ((*a == *b) ? 0 : 1);
-
- I think I prefer to avoid the multiple dereferencing with:
-
- static int sort_func(const void *pa, const void *pb)
- {
- int a = *(const int *)pa;
- int b = *(const int *)pb;
-
- return a < b ? -1 : a > b;
- }
- --
- walter briscoe
-